package com.zmj.mobile.process;

import com.zmj.framework.response.Result;
import com.zmj.framework.util.ThreadContextHandler;
import com.zmj.mobile.dto.AuditDTO;
import com.zmj.mobile.entity.TechPurMainEntity;
import com.zmj.mobile.enums.FlowTypeEnum;
import com.zmj.mobile.mapper.ITechPurMainMapper;
import com.zmj.modules.flow.entity.dto.BpmProcessStartQueryDto;
import com.zmj.modules.flow.entity.dto.BpmTaskQueryDto;
import com.zmj.modules.flow.entity.vo.ProcessInstanceVO;
import com.zmj.modules.flow.service.FlowableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class TechPurAuditServiceImpl implements IAuditService {

    @Resource
    private FlowableService flowableService;
    @Resource
    private ITechPurMainMapper techPurMainMapper;

    @Override
    public boolean agree(IAudit audit) {
        AuditDTO auditDTO = (AuditDTO) audit;
        Long id = auditDTO.getId();

        //调用流程接口进入审核流程
        BpmProcessStartQueryDto bpmProcessStartQueryDto = getBpmProcessStartQueryDto(id);
        Result<ProcessInstanceVO> result = flowableService.startProcessInstance(bpmProcessStartQueryDto);
        // 流程的id
        String procInstId = result.getData().getProcInstId();
        //todo
        TechPurMainEntity entity = TechPurMainEntity.builder().id(id).dataStatus("").flowId(procInstId).build();
        techPurMainMapper.updateById(entity);
        // 任务处理ID
        String username = ThreadContextHandler.getCurrentUser().getUsername();
        String taskId = result.getData().getUserTaskInfos().get(0).getTaskId();
        BpmTaskQueryDto bpmTaskQueryDto = new BpmTaskQueryDto(taskId, username, null, "", null, null);
        flowableService.agree(bpmTaskQueryDto);
        return true;

    }

    @Override
    public boolean reject(IAudit audit) {
        return false;
    }

    private BpmProcessStartQueryDto getBpmProcessStartQueryDto(Long id) {
        //todo
        Map<String, Object> map = new HashMap<>();
        map.put("businessKey", id);

        BpmProcessStartQueryDto bpmProcessStartQueryDto = new BpmProcessStartQueryDto();
        bpmProcessStartQueryDto.setVariables(map);
        bpmProcessStartQueryDto.setCurrentUserId(ThreadContextHandler.getCurrentUser().getUsername());
        bpmProcessStartQueryDto.setKey(FlowTypeEnum.TECH_PUR_MAIN.getKey());
        return bpmProcessStartQueryDto;
    }
}
